package com.cslg.ac.demo.service.text;

import com.cslg.ac.demo.constant.TextType;
import com.cslg.ac.demo.util.string.StringUtil;
import org.springframework.stereotype.Service;

@Service
public class TextFilterService {


    private static final String[] REPLACE_CHARS = { "<",">", "\"", " "};
    private static final String[] REPLACE_STRING = {"&quot;", "&lt;", "&gt;","&nbsp;", "&amp;"};
    /**
     * 这里不知道怎么替换掉客户端没有检查的&
     * @param text
     * @return
     */
    private boolean checkChar(String text){

        for(int i = 0;i < REPLACE_CHARS.length;i++){
            if(text.contains(REPLACE_CHARS[i])){
                return false;
            }
        }
        return true;
    }

    private String replaceChar(String text){
        return text.replaceAll(REPLACE_STRING[0], "\"")
                .replaceAll(REPLACE_STRING[1], "<")
                .replaceAll(REPLACE_STRING[2], ">")
                .replaceAll(REPLACE_STRING[3], " ")
                .replaceAll(REPLACE_STRING[4], "&");
    }

    public String getFilterString(String text, int textType){
        if(StringUtil.haveNullOrEmpty(text)){
            return text;
        }
        if(!checkChar(text)){
            return null;
        }
        text = replaceChar(text);
        switch (textType){
            case TextType.POST_TYPE:
                break;
                default:return text;
        }
        return text;
    }
}
